package cn.edu.zucc.JavaChat.ChatClient.Model;

import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultListModel;

import cn.edu.zucc.JavaChat.Bean.User;
import cn.edu.zucc.JavaChat.ChatClient.UserCenterClient;

public class FriendListModel extends DefaultListModel<Object> {
	
	private static final long serialVersionUID = 1L;

	synchronized public void setNewMessage(String username, boolean isNewMessage){
		for(int i = 0;i < this.size();i++){
			Object[] e = (Object[])this.getElementAt(i);
			if(((User)e[0]).getUsername().equals(username)){
				e[1] = isNewMessage;
			}
		}
		refresh();
	}
	synchronized public void setUserList(List<User> userList){
		this.removeAllElements();
		for(User item : userList){
			this.addElement(new Object[]{item, 
					UserCenterClient.getInstance()
					.isNewMessage(item.getUsername())});
		}
		
	}
	
	synchronized public void setOnline(String username, boolean isOnline){
		for(int i = 0;i < this.size();i++){
			Object[] e = (Object[])this.getElementAt(i);
			if(((User)e[0]).getUsername().equals(username)){
				((User)e[0]).setOnline(isOnline);
			}
		}
		refresh();
	}
	

	synchronized public String getUsername(int selectedIndex) {
		Object[] e = (Object[])this.getElementAt(selectedIndex);
		return ((User)e[0]).getUsername();
	}
	
	synchronized public void refresh(){
		List<Object> es = new ArrayList<Object>();
		for(int i = 0; i < this.size(); i++){
			es.add(this.getElementAt(i));
		}
		this.removeAllElements();
		for(Object item : es){
			this.addElement(item);
		}
	}
	
}
